package api

import (
	"api-gateway/pkg"
	"github.com/gin-gonic/gin"
	"net/http"
	"path/filepath"
)

func Upload(c *gin.Context) {
	file, err := c.FormFile("file")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  err,
		})
		return
	}

	if file.Size > 200*1024 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "图片过大，请上传小于200KB的图片",
		})
		return
	}

	ext := filepath.Ext(file.Filename)
	if ext != ".png" {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "图片格式错误，请上传格式为png图片",
		})
		return
	}

	upload, err := pkg.Upload(file)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "上传失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "上传成功",
		"url":  upload,
	})
}
